//
//  HXDNetworkTools.swift
//  swiftHTTP
//
//  Created by huxuedong on 15/12/6.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import AFNetworking

enum HXDRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class HXDNetworkTools: AFHTTPSessionManager {
    
    //为回调的闭包定义别名
    typealias HXDNetworkToolsBack = (response: AnyObject?, error: NSError?) -> ()
    static let shareTools: HXDNetworkTools = {
        let instence = HXDNetworkTools()
        //设置解析类型(NSSet会自动转换为Set)
        instence.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instence
    }()
    
    func request(method method: HXDRequestMethod, url: String, parameter: AnyObject?, back: HXDNetworkToolsBack) {
        //成功回调闭包
        let successBack = {(dataTask: NSURLSessionDataTask, response: AnyObject) -> () in
            back(response: response, error: nil)
        }
        //失败回调闭包
        let failureBack = {(dataTask: NSURLSessionDataTask?, error: NSError) -> () in
            back(response: nil, error: error)
        }
        if method == .GET {
            self.GET(url, parameters: parameter, success: successBack, failure: failureBack)
        } else {
            self.POST(url, parameters: parameter, success: successBack, failure: failureBack)
        }
    }
    
    func requestContainImage(url urlString: String, parameter: AnyObject?, data: NSData, name: String, back: HXDNetworkToolsBack) {
        //成功回调闭包
        let successBack = {(dataTask: NSURLSessionDataTask, response: AnyObject) -> () in
            back(response: response, error: nil)
        }
        //失败回调闭包
        let failureBack = {(dataTask: NSURLSessionDataTask?, error: NSError) -> () in
            back(response: nil, error: error)
        }
        POST(urlString, parameters: parameter, constructingBodyWithBlock: { (formData) -> Void in
            //拼装NSData
            formData.appendPartWithFileData(data, name: name, fileName: "任意字符串均可", mimeType: "application/octet-stream")
            }, success: successBack, failure: failureBack)
    }
    
}

//获取用户信息
extension HXDNetworkTools {
    
    func loadAccessToken(code: String, back: HXDNetworkToolsBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameter = [
            "client_id": kAppKey,
            "client_secret": kAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": kRedirect_uri
        ]
        request(method: .POST, url: urlString, parameter: parameter, back: back)
    }
    
    func loadUserInfo(uid: String, accessToken: String, back: HXDNetworkToolsBack) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameter = [
            "access_token": accessToken,
            "uid": uid
        ]
        request(method: .GET, url: urlString, parameter: parameter, back: back)
    }
    
}

//加载微博数据
extension HXDNetworkTools {
    
    func loadStatus(accessToken: String, maxId: Int64 = 0, sinceId: Int64 = 0, back: HXDNetworkToolsBack) {
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let parameter = [
            "access_token": accessToken,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        request(method: .GET, url: urlString, parameter: parameter, back: back)
    }
    
}

//发微博
extension HXDNetworkTools {
    
    //发送文字微博
    func upData(accessToken: String, status: String, back: HXDNetworkToolsBack) {
        let url = "https://api.weibo.com/2/statuses/update.json"
        let parameter = [
            "access_token": accessToken,
            "status": status
        ]
        request(method: .POST, url: url, parameter: parameter, back: back)
    }
    
    //发送图片微博
    func upLoadContainImage(accessToken: String, status: String, image: UIImage, back: HXDNetworkToolsBack) {
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let parameter = [
            "access_token": accessToken,
            "status": status
        ]
        //将图片转换成NSData数据
        let data = UIImagePNGRepresentation(image)!
        requestContainImage(url: url, parameter: parameter, data: data, name: "pic", back: back)
    }
    
}
